//
//  LoginViewController.m
//  CPICApp
//
//  Created by sinosoft on 13-3-8.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "RCAlertViewUtil.h"
#import "ASIHTTPRequest.h"
#import "Config.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"
#import "AppDelegate.h"
#import "AccountSettingViewController.h"
#import "ViewController.h"
#import "RCAutoGlobal.h"
#import "UIImageView+WebCache.h"
#import "RCSoftUpdate.h"
#import "RCUpdateNotice.h"

@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize TableViewUser,TableViewCity;
@synthesize txtUserAccount,txtUserPassword,txtLoginType,txtLoginCity;
@synthesize progress;
@synthesize touchQQ,touchSina;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"用户登录");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"用户登录");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"用户登录");
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }
    
    //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    AppDelegate *appMyDelegate=[[UIApplication sharedApplication]delegate];
    appMyDelegate.iLoginorAccountTag=1;
    
    arrUser=[[NSMutableArray alloc]initWithObjects:@"用户账号",@"用户密码",@"登录类型", nil];
    arrLoginType=[[NSMutableArray alloc]initWithObjects:@"本系统用户",@"新浪微博用户",@"QQ用户", nil];
    arrLoginCity=[[NSMutableArray alloc]initWithObjects:@"深圳市",@"非深圳市", nil];
    txtUserAccount=[[UITextField alloc]initWithFrame:CGRectMake(100, 10, 180, 31)];
    txtUserAccount.delegate=self;
    txtUserAccount.borderStyle=UITextBorderStyleBezel;
    txtUserAccount.returnKeyType=UIReturnKeyDone;
    
    txtUserPassword=[[UITextField alloc]initWithFrame:CGRectMake(100, 10, 145, 31)];
    txtUserPassword.delegate=self;
    txtUserPassword.borderStyle=UITextBorderStyleBezel;
    txtUserPassword.returnKeyType=UIReturnKeyDone;
    txtUserPassword.secureTextEntry=YES;
    
    txtLoginType=[[UITextField alloc]initWithFrame:CGRectMake(100, 10, 145, 31)];
    txtLoginType.delegate=self;
    txtLoginType.borderStyle=UITextBorderStyleBezel;
    txtLoginType.returnKeyType=UIReturnKeyDone;
    
    txtLoginCity=[[UITextField alloc]initWithFrame:CGRectMake(100, 10, 145, 31)];
    txtLoginCity.delegate=self;
    txtLoginCity.borderStyle=UITextBorderStyleBezel;
    txtLoginCity.returnKeyType=UIReturnKeyDone;
    txtLoginCity.enabled=NO;
    txtLoginCity.text=@"深圳市";
    
    //添加UITableview
    TableViewUser = [[UITableView alloc]initWithFrame:CGRectMake(8, 65, 310, 170) style:UITableViewStyleGrouped];
	TableViewUser.delegate = self;
	TableViewUser.dataSource = self;
    
    TableViewUser.opaque = NO;
    TableViewUser.backgroundView = nil;
    TableViewUser.autoresizingMask = UIViewContentModeTop;
    TableViewUser.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    TableViewUser.scrollEnabled=NO;
    TableViewUser.backgroundColor=[UIColor clearColor];
    //[TableViewUser reloadData];
	[self.view addSubview:TableViewUser];
    
    
    TableViewCity = [[UITableView alloc]initWithFrame:CGRectMake(8, 164, 310, 70) style:UITableViewStyleGrouped];
	TableViewCity.delegate = self;
	TableViewCity.dataSource = self;
    
    TableViewCity.opaque = NO;
    TableViewCity.backgroundView = nil;
    TableViewCity.autoresizingMask = UIViewContentModeTop;
    TableViewCity.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    TableViewCity.scrollEnabled=NO;
    TableViewCity.backgroundColor=[UIColor clearColor];
    //[TableViewPassword reloadData];
	[self.view addSubview:TableViewCity];
    
    UIButton *btnLogin=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnLogin.frame=CGRectMake(20, 260, 241/2, 63/2);
    [btnLogin setImage:[UIImage imageNamed:@"login_btn.png"] forState:UIControlStateNormal];
    [btnLogin addTarget:self action:@selector(LoginButtonTap:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btnRegister=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnRegister.frame=CGRectMake(180, 260, 241/2, 63/2);
    [btnRegister setImage:[UIImage imageNamed:@"reg_btn.png"] forState:UIControlStateNormal];
    [btnRegister addTarget:self action:@selector(RegisterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnLogin];
    [self.view addSubview:btnRegister];
    
    UIButton *btnSinaLogin=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnSinaLogin.frame=CGRectMake(70, 320, 180, 40);
    //[btnSinaLogin setTitle:@"新浪用户登录" forState:UIControlStateNormal];
    [btnSinaLogin setBackgroundImage:[UIImage imageNamed:@"sinaLogin.png"] forState:UIControlStateNormal];
    [btnSinaLogin addTarget:self action:@selector(SinaBtnTap:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSinaLogin];
    
    UIButton *btnQQLogin=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnQQLogin.frame=CGRectMake(70, 390, 180, 40);
    //[btnQQLogin setTitle:@"QQ用户登录" forState:UIControlStateNormal];
    [btnQQLogin setBackgroundImage:[UIImage imageNamed:@"qqLogin.png"] forState:UIControlStateNormal];
    [btnQQLogin addTarget:self action:@selector(QQBtnTap:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnQQLogin];
    
    _permissions = [[NSArray arrayWithObjects:
                     kOPEN_PERMISSION_GET_USER_INFO,
                     kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                     kOPEN_PERMISSION_ADD_ALBUM,
                     kOPEN_PERMISSION_ADD_IDOL,
                     kOPEN_PERMISSION_ADD_ONE_BLOG,
                     kOPEN_PERMISSION_ADD_PIC_T,
                     kOPEN_PERMISSION_ADD_SHARE,
                     kOPEN_PERMISSION_ADD_TOPIC,
                     kOPEN_PERMISSION_CHECK_PAGE_FANS,
                     kOPEN_PERMISSION_DEL_IDOL,
                     kOPEN_PERMISSION_DEL_T,
                     kOPEN_PERMISSION_GET_FANSLIST,
                     kOPEN_PERMISSION_GET_IDOLLIST,
                     kOPEN_PERMISSION_GET_INFO,
                     kOPEN_PERMISSION_GET_OTHER_INFO,
                     kOPEN_PERMISSION_GET_REPOST_LIST,
                     kOPEN_PERMISSION_LIST_ALBUM,
                     kOPEN_PERMISSION_UPLOAD_PIC,
                     kOPEN_PERMISSION_GET_VIP_INFO,
                     kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                     kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                     kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                     nil] retain];
    NSString *appid = @"222222";
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
											andDelegate:self];
}

-(void)SinaBtnTap:(id)sender
{
    touchSina=YES;
    touchQQ=NO;
    
    AppDelegate *appMyDelegate=[[UIApplication sharedApplication]delegate];
    appMyDelegate.iLoginorAccountTag=1;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    NSLog(@"%@", [keyWindow subviews]);
    [userInfo release], userInfo = nil;
    [statuses release], statuses = nil;
    SinaWeibo *sinaweibo = [self sinaweibo];
    if ([sinaweibo isAuthValid])
    {
        [ self setBindCheckRequest];
    }
    else
    {
        [sinaweibo logIn];
    }
    
    
    
}

-(void)checkSinaAuth
{

    AppDelegate *appMyDelegate=[[UIApplication sharedApplication]delegate];
    appMyDelegate.iLoginorAccountTag=1;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    NSLog(@"%@", [keyWindow subviews]);
    
    
    [userInfo release], userInfo = nil;
    [statuses release], statuses = nil;
    
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    if ([sinaweibo isAuthValid]) {
        //                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"你已经授权新浪微博" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"注销", nil];
        //                [alert show];
        //                [alert release];
        if (bindingSina==NO) {
            UIAlertView *alert1=[[UIAlertView alloc]initWithTitle:@"注意" message:@"你已经授权新浪微博,但还没绑定本系统账户,是否立即跳到绑定页面" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定绑定",@"注销新浪微博", nil];
            alert1.tag=1;
            [alert1 show];
            [alert1 release];
        }
        else
        {
            UIAlertView *alert1=[[UIAlertView alloc]initWithTitle:@"提示" message:@"登录成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"注销新浪微博", nil];
            alert1.tag=2;
            [alert1 show];
            [alert1 release];
        }
        
    }
    else
    {
        [sinaweibo logIn];
    }
    

}

-(void)QQBtnTap:(id)sender
{
    touchQQ=YES;
    touchSina=NO;
    if([_tencentOAuth isSessionValid])
    {
        [self setBindCheckRequest];
    }
    else
    {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    }
    
    
}

-(void)checkQQAuth
{
    if([_tencentOAuth isSessionValid])
    {
        if (bindingQQ==NO) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"你已经授权QQ账户,但还没绑定本系统账户,是否立即跳到绑定页面" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定绑定",@"注销QQ用户", nil];
            alert.tag=4;
            [alert show];
            [alert release];
        }
        else
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"登录成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"注销QQ用户", nil];
            alert.tag=5;
            [alert show];
            [alert release];
            
        }
    }
    else
    {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    }
    

}
-(void)LoginButtonTap:(id)sender
{
    if (txtUserAccount.text.length==0) {
        [self justShowMessage:@"用户账号不能为空" title:@"注意"];
        return;
    }
    if (txtUserPassword.text.length==0) {
        [self justShowMessage:@"用户密码不能为空" title:@"注意"];
        return;
    }
//    if (txtLoginType.text.length==0) {
//        [self justShowMessage:@"请选择登录类型" title:@"注意"];
//        return;
//    }
    if (txtLoginCity.text.length==0) {
        [self justShowMessage:@"请选择登录城市" title:@"注意"];
        return;
    }
    [self setRequest];
}

-(void)RegisterButtonTap:(id)sender
{
    RegisterViewController *registerViewCtrl=[[RegisterViewController alloc]init];
    [self.navigationController pushViewController:registerViewCtrl animated:YES];
    [registerViewCtrl release];
}
-(void) ClickCallOutBtn
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)setRequest//向太保移动平台发送请求报文
{
//    NSString *strRequestCode=@"RequestCode=60101";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    if(self.txtUserAccount.text.length!=0)
    {
        [dicRequest setObject:self.txtUserAccount.text forKey:@"userAccount"];
    }
    else
    {
        [dicRequest setObject:@"" forKey:@"userAccount"];
    }
    
    if(self.txtUserPassword.text.length!=0)
    {
        [dicRequest setObject:self.txtUserPassword.text forKey:@"userPassword"];
    }
    else
    {
        [dicRequest setObject:@"" forKey:@"userPassword"];
    }
    if ([self.txtLoginCity.text isEqualToString:@"深圳市"]) {
        strLoginCityCode=@"UC_00";
    }
    else if([self.txtLoginCity.text isEqualToString:@"非深圳市"])
    {
        strLoginCityCode=@"UC_01";
    }
    else
    {
        strLoginCityCode=@"";
    }
    [dicRequest setObject:strLoginCityCode forKey:@"loginCity"];
//    if(self.txtLoginCity.text.length!=0)
//    {
//        [dicRequest setObject:self.txtLoginCity.text forKey:@"loginCity"];
//    }
//    else
//    {
//        [dicRequest setObject:@"" forKey:@"loginCity"];
//    }
    
    if(self.txtLoginType.text.length!=0)
    {
        [dicRequest setObject:@"0" forKey:@"loginType"];
    }
    else
    {
        [dicRequest setObject:@"0" forKey:@"loginType"];
    }
    
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"60101" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictResponse objectForKey:@"userAccount"]];
    NSString *strUserName= [[NSString alloc] initWithFormat:@"%@",[dictResponse objectForKey:@"userName"]];
    NSLog(@"strResult %@",strResult);
    if (strResult.length!=0) {
        [self justShowMessage:@"登录成功" title:nil];
        NSDictionary *dictUserInfo=[[NSDictionary alloc]initWithObjectsAndKeys:strResult,@"UserAccount",txtLoginCity.text,@"LoginCity",@"0",@"LoginType",strUserName,@"UserName", nil];
        NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
        [myDefaults setObject:dictUserInfo forKey:DICT_USER_INFO];
        NSLog(@"userdefaults%@",[myDefaults objectForKey:DICT_USER_INFO]);
        if (dictUserInfo!=nil) {
            if ([dictUserInfo valueForKey:@"UserAccount"]) {
                [myDefaults setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:Login_UserAccount];
            }
            else
            {
            }
        }
        else
        {
        }
        NSDictionary *dictCustomerInfo=[[NSDictionary alloc]initWithObjectsAndKeys:@"",@"userName",@"",@"idNo",@"",@"license",@"",@"phone",@"",@"email",@"",@"postalAddress",@"",@"debutdate", nil];
        [myDefaults setObject:dictCustomerInfo forKey:DICT_CUSTOMER_INFO];
//        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//        delegate.viewController.lblUserName.text=strUserName;
        for (UIViewController *objectView in [AppDelegate app].unc.viewControllers) {
            if ([objectView isKindOfClass:[ViewController class]]) {
                ViewController *viewctrl=(ViewController *)objectView;
                
                viewctrl.lblUserName.text=strUserName;
                viewctrl.btnCancel.hidden=NO;
                viewctrl.LoginInOrOut=NO;
                [viewctrl.btnCancel setImage:[UIImage imageNamed:@"Loginout.png"] forState:UIControlStateNormal];
                [self getNoticeNum];
            }
        }
        //[delegate.viewController updateVersion];
        [self SETCustomerQueryRequest];
        
        
    }
    else
    {
        [self justShowMessage:[dictHead objectForKey:@"message"] title:nil];
    }
    [strResult release];
    
    
}

-(void)SETCustomerQueryRequest;//向太保移动平台发送客户资料查询请求报文
{
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil)
    {
        if ([dictUserInfo valueForKey:@"UserAccount"])
        {
            //NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
        //[self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        return;
    }
    
    //    NSString *strRequestCode=@"RequestCode=62201";
    NSString *strRequestData=[NSString stringWithFormat:@"{\"userAccount\":\"%@\"}",[dictUserInfo valueForKey:@"UserAccount"]];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"62201" forKey:@"RequestCode"];
    [request setPostValue:strRequestData forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail1:)];
    [request setDidFinishSelector:@selector(ResonseSuccess1:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress)
    {
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"加载中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSuccess1:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString------%@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSMutableDictionary *jsonoSubObj = [dictResponse objectForKey:@"head"];
    NSString * ss = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"success"]];
    
    if ([ss isEqualToString:@"1"])
    {
        
        NSDictionary *dictCustomerInfo=[[NSDictionary alloc]initWithObjectsAndKeys:[dictResponse objectForKey:@"userName"],@"userName",[dictResponse objectForKey:@"idNo"],@"idNo",[dictResponse objectForKey:@"contactPhone"],@"phone",[dictResponse objectForKey:@"email"],@"email",[dictResponse objectForKey:@"postalAddress"],@"postalAddress",[dictResponse valueForKey:@"debutdate"],@"debutdate", nil];
        NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
        [myDefaults setObject:dictCustomerInfo forKey:DICT_CUSTOMER_INFO];
        NSLog(@"userdefaults%@",[myDefaults objectForKey:DICT_CUSTOMER_INFO]);
    }
    else
    {
        //[self justShowMessage:@"获取客户资料信息失败！" title:@"提示"];
        return;
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)ResponseFail1:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败！" title:@"提示"];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)getNoticeNum
{
    RCUpdateNotice *rcUpdateNotice=[[RCUpdateNotice alloc]initUpdateNoticeView];
    [rcUpdateNotice setNoticeRequest];
    [rcUpdateNotice setHidden:YES];
    [self.view addSubview:rcUpdateNotice];
    [rcUpdateNotice release];
}
- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

-(void)setBindCheckRequest//向太保移动平台发送请求报文
{
//    NSString *strRequestCode=@"RequestCode=62102";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    if (touchSina==NO && touchQQ==YES) {
        if (QQopenId.length!=0) {
            [dicRequest setValue:QQopenId forKey:@"UserId"];
        }
        else
        {
            [dicRequest setValue:@"" forKey:@"UserId"];
        }
        [dicRequest setValue:@"2" forKey:@"bindingType"];
    }
    if (touchQQ==NO && touchSina==YES) {
        SinaWeibo *sinaweibo = [self sinaweibo];
        [dicRequest setValue:sinaweibo.userID forKey:@"UserId"];
        [dicRequest setValue:@"1" forKey:@"bindingType"];
    }
    [dicRequest setValue:@"" forKey:@"userAccount"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"62102" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseBindCheckFail:)];
    [request setDidFinishSelector:@selector(ResonseBindCheckSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseBindCheckSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    strUserAccountQQSina=[dictResponse objectForKey:@"userAccount"];
    strUserNameQQSina=[dictResponse objectForKey:@"userName"];
   // if ([strResult isEqualToString:@"1"]) {
        if (strUserAccountQQSina.length!=0) {
            //[self justShowMessage:@"登录成功" title:nil];
            if (touchSina==YES && touchQQ==NO)
            {
                RCUserInfo *USERinfo=[[RCUserInfo alloc]init];
                [USERinfo setUserAccount:strUserAccountQQSina];
                [USERinfo setSinaUserID:[dictResponse objectForKey:@"userId"]];
                RCAutoGlobal *autoGlobal=[RCAutoGlobal sharedRCAutoGlobal];
                [autoGlobal setRcUserInfo:USERinfo];
                bindingSina=YES;
                [self checkSinaAuth];
            }
            if (touchQQ==YES && touchSina==NO) {
                RCUserInfo *USERinfo=[[RCUserInfo alloc]init];
                [USERinfo setUserAccount:strUserAccountQQSina];
                [USERinfo setQQUserID:[dictResponse objectForKey:@"userId"]];
                RCAutoGlobal *autoGlobal=[RCAutoGlobal sharedRCAutoGlobal];
                [autoGlobal setRcUserInfo:USERinfo];
                bindingQQ=YES;
                [self checkQQAuth];
            }
        }
        else
        {
            //[self justShowMessage:@"登录失败" title:nil];
            if (touchSina==YES && touchQQ==NO)
            {
                bindingSina=NO;
                [self checkSinaAuth];
            }
            if (touchQQ==YES && touchSina==NO) {
                bindingQQ=NO;
                [self checkQQAuth];
            }
        }

//    }
//    else
//    {
//
//    }
    [strResult release];
    
    
}

- (void)ResponseBindCheckFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView==TableViewUser)
    {
        return 2;
    }
    else
    {
        return 1;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView==TableViewUser)
    {
        static NSString *Identifier=@"Identifier";
        UITableViewCell *cell=(UITableViewCell *)[TableViewUser dequeueReusableCellWithIdentifier:Identifier];
        if (cell==nil)
        {
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle=UITableViewCellSelectionStyleNone;//选中后颜色没变化
        }
        
        UILabel *lblUserAccount=[[UILabel alloc]initWithFrame:CGRectMake(20, 10, 85, 21)];
        lblUserAccount.backgroundColor=[UIColor clearColor];
        lblUserAccount.text=[arrUser objectAtIndex:indexPath.row];
        [cell addSubview:lblUserAccount];
        [lblUserAccount release];
        
        UIImage *image= [ UIImage imageNamed:@"login_type.png" ];
        UIButton *button = [ UIButton buttonWithType:UIButtonTypeCustom ];
        CGRect frame = CGRectMake( 25.0 , 5.0 , 58/2 , 49/2 );
        button. frame = frame;
        [button setBackgroundImage:image forState:UIControlStateNormal ];
        button. backgroundColor = [UIColor clearColor ];
        
        UIButton *btnForget = [ UIButton buttonWithType:UIButtonTypeInfoDark ];
        CGRect btnFrame = CGRectMake( 25.0 , 5.0 ,35 , 30 );
        btnForget. frame = btnFrame;
        btnForget. backgroundColor = [UIColor clearColor ];
        
        if(indexPath.row==0)
        {
            NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
            if ([myDefaults valueForKey:@"Login_UserAccount"])
            {
                txtUserAccount.text=[myDefaults valueForKey:@"Login_UserAccount"];
            }
            else
            {
            }
            [cell addSubview:txtUserAccount];
        }
        else if(indexPath.row==1)
        {
            
            [cell addSubview:txtUserPassword];
            [btnForget addTarget:self action:@selector(fotgetPassword) forControlEvents:UIControlEventTouchUpInside];
            cell.accessoryView=btnForget;
            [cell addSubview:btnForget];
        }
        else if(indexPath.row==2)
        {

            [button addTarget:self action:@selector(setLoginType) forControlEvents:UIControlEventTouchUpInside];
            cell.accessoryView=button;
            
            [cell addSubview:txtLoginType];
        }
        return cell;
    }
    else
    {
        static NSString *Identifier=@"Identifier";
        UITableViewCell *cell=(UITableViewCell *)[TableViewUser dequeueReusableCellWithIdentifier:Identifier];
        if (cell==nil)
        {
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        UILabel *lblUserPassword=[[UILabel alloc]initWithFrame:CGRectMake(25, 10, 116, 21)];
        lblUserPassword.backgroundColor=[UIColor clearColor];
        lblUserPassword.text=@"登录城市";
        [cell addSubview:lblUserPassword];
        [lblUserPassword release];
        
        UIImage *image= [ UIImage imageNamed:@"login_type.png" ];
        UIButton *button = [ UIButton buttonWithType:UIButtonTypeCustom ];
        CGRect frame = CGRectMake( 25.0 , 5.0 , 58/2 , 49/2 );
        button. frame = frame;
        [button setBackgroundImage:image forState:UIControlStateNormal ];
        button. backgroundColor = [UIColor clearColor ];
        if(indexPath.row==0)
        {

            [button addTarget:self action:@selector(setLoginCity) forControlEvents:UIControlEventTouchUpInside];
            cell.accessoryView=button;
            [cell addSubview:txtLoginCity];
        }
        
        return cell;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(textField==txtLoginType)
    {
        [self SetAnimation:50];
    }
    else if(textField==txtLoginCity)
    {
        [self SetAnimation:100];
    }

}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField==txtLoginType)
    {
        [self backAnimation:50];
    }
    else if(textField==txtLoginCity)
    {
        [self backAnimation:100];
    }
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField==txtUserAccount)
    {
        if(range.location>=50)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    else if(textField==txtUserPassword)
    {
        if(range.location>=20)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    else if(textField==txtLoginCity)
    {
        if(range.location>=10)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    else if(textField==txtLoginType)
    {
        if(range.location>=20)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
     return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)SetAnimation:(CGFloat)Xorigin
{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    //frame.origin.x+=Xorigin;
    frame.origin.y-=Xorigin;
    //frame.size.height +=Xorigin;
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
}

-(void)backAnimation:(CGFloat)Xorigin
{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    //frame.origin.x -=Xorigin;
    frame.origin.y+=Xorigin;
    //frame.size.height -=Xorigin;
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
    // [textField resignFirstResponder];
}
-(void)setLoginCity
{
    CustomActionSheet *sheet=[[CustomActionSheet alloc]initWithHeight:284.0f WithSheetTitle:@"" WithDataArray:arrLoginCity];
    sheet.tag=1;
    sheet.Customdelegate=self;
    [sheet showInView:self.view];
}
-(void)setLoginType
{
    CustomActionSheet *sheet=[[CustomActionSheet alloc]initWithHeight:284.0f WithSheetTitle:@"" WithDataArray:arrLoginType];
    sheet.tag=0;
    sheet.Customdelegate=self;
    [sheet showInView:self.view];
}

-(void)fotgetPassword
{
    [self justShowMessage:@"请联系95500客服人员修改密码!" title:@"忘记密码?"];
}
-(void)ClickItem:(NSString *)Title ActionSheetTag:(NSInteger)actionSheetTag
{
    if (actionSheetTag==0) {
        self.txtLoginType.text=Title;
        
        if ([Title isEqualToString:@"新浪微博用户"]) {
            
            UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
            NSLog(@"%@", [keyWindow subviews]);
            
            
            [userInfo release], userInfo = nil;
            [statuses release], statuses = nil;
            
            SinaWeibo *sinaweibo = [self sinaweibo];
            
            
            if ([sinaweibo isAuthValid]) {

                if (bindingSina==NO) {
                    UIAlertView *alert1=[[UIAlertView alloc]initWithTitle:@"注意" message:@"你已经授权新浪微博,但还没绑定本系统账户,是否立即跳到绑定页面" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",@"注销新浪微博", nil];
                    alert1.tag=1;
                    [alert1 show];
                    [alert1 release];
                }
                else
                {
                    UIAlertView *alert1=[[UIAlertView alloc]initWithTitle:@"注意" message:@"你已经绑定本系统账户" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"注销新浪微博", nil];
                    alert1.tag=2;
                    [alert1 show];
                    [alert1 release];
                }

            }
            else
            {
                [sinaweibo logIn];
            }
        }
        else if([Title isEqualToString:@"QQ用户"])
        {
            [_tencentOAuth authorize:_permissions inSafari:NO];
        }
    }
    else if(actionSheetTag==1)
    {
        self.txtLoginCity.text=Title;
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    if (alertView.tag==1) {
        
        if (buttonIndex==0) {
              
        }
        else if(buttonIndex==1)
        {
            
            AccountSettingViewController *accountSettingViewCtrl=[[AccountSettingViewController alloc]init];
            [self.navigationController pushViewController:accountSettingViewCtrl animated:YES];
            accountSettingViewCtrl.imgAccount.image=[UIImage imageNamed:@"sinaLogo.png"];
            [accountSettingViewCtrl setSinaItemTitle];
            accountSettingViewCtrl.sinaAccount=YES;
            accountSettingViewCtrl.qqAccount=NO;
            [accountSettingViewCtrl release];
        }
        else if(buttonIndex==2)
        {
            [sinaweibo logOut];
        }
        else
        {

        }
    }
    else if(alertView.tag==2)
    {
        if (buttonIndex==0) {
            NSDictionary *dictUserInfo=[[NSDictionary alloc]initWithObjectsAndKeys:strUserAccountQQSina,@"UserAccount",strUserNameQQSina,@"UserName",txtLoginCity.text,@"LoginCity",@"1",@"LoginType", nil];
            [[NSUserDefaults standardUserDefaults] setObject:dictUserInfo forKey:DICT_USER_INFO];
            
            //清空缓存数据
            NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
            NSDictionary *dictCustomerInfo=[[NSDictionary alloc]initWithObjectsAndKeys:@"",@"userName",@"",@"idNo",@"",@"license",@"",@"phone",@"",@"email",@"",@"postalAddress",@"",@"debutdate", nil];
            [myDefaults setObject:dictCustomerInfo forKey:DICT_CUSTOMER_INFO];
            if (dictUserInfo!=nil) {
                if ([dictUserInfo valueForKey:@"UserAccount"]) {
                    [myDefaults setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:Login_UserAccount];
                }
                else
                {
                }
            }
            else
            {
            }
            //
    
//            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//            delegate.viewController.lblUserName.text=strUserNameQQSina;
            for (UIViewController *objectView in [AppDelegate app].unc.viewControllers) {
                if ([objectView isKindOfClass:[ViewController class]]) {
                    ViewController *viewctrl=(ViewController *)objectView;
                    
                    viewctrl.lblUserName.text=strUserNameQQSina;
                    viewctrl.btnCancel.hidden=NO;
                    viewctrl.LoginInOrOut=NO;
                    [viewctrl.btnCancel setImage:[UIImage imageNamed:@"Loginout.png"] forState:UIControlStateNormal];
                    [self getNoticeNum];
                }
            }
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else if(buttonIndex==1)
        {
             [sinaweibo logOut];
        }
        else
        {
           
        }
    }
    else if(alertView.tag==3)
    {
    
        if(buttonIndex==0)
        {
            AccountSettingViewController *accountSettingViewCtrl=[[AccountSettingViewController alloc]init];
            [[AppDelegate app].unc pushViewController:accountSettingViewCtrl animated:YES];
            accountSettingViewCtrl.imgAccount.image=[UIImage imageNamed:@"sinaLogo.png"];
            [accountSettingViewCtrl setSinaItemTitle];
            accountSettingViewCtrl.sinaAccount=YES;
            accountSettingViewCtrl.qqAccount=NO;
            [accountSettingViewCtrl release];
        }
        else if(buttonIndex==1)
        {
            
        }
        else{
            
        }
    }
    else if(alertView.tag==4)
    {
        if(buttonIndex==0)
        {
            
        }
        else if(buttonIndex==1)
        {
            AccountSettingViewController *accountSettingViewCtrl=[[AccountSettingViewController alloc]init];
            [[AppDelegate app].unc  pushViewController:accountSettingViewCtrl animated:YES];
            accountSettingViewCtrl.imgAccount.image=[UIImage imageNamed:@"qqLogo.png"];
            accountSettingViewCtrl.QQopenId=QQopenId;
            [accountSettingViewCtrl setQQItemTitle];
            accountSettingViewCtrl.qqAccount=YES;
            accountSettingViewCtrl.sinaAccount=NO;
        }
        else if(buttonIndex==2)
        {
            [_tencentOAuth logout:self];
        }
        else if(buttonIndex==3)
        {
    
        }
    
    }
    else if(alertView.tag==5)
    {
        if (buttonIndex==0) {
            NSDictionary *dictUserInfo=[[NSDictionary alloc]initWithObjectsAndKeys:strUserAccountQQSina,@"UserAccount",strUserNameQQSina,@"UserName",txtLoginCity.text,@"LoginCity",@"2",@"LoginType", nil];
            [[NSUserDefaults standardUserDefaults] setObject:dictUserInfo forKey:DICT_USER_INFO];
            
            //清空缓存数据
            NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
            NSDictionary *dictCustomerInfo=[[NSDictionary alloc]initWithObjectsAndKeys:@"",@"userName",@"",@"idNo",@"",@"license",@"",@"phone",@"",@"email",@"",@"postalAddress",@"",@"debutdate", nil];
            [myDefaults setObject:dictCustomerInfo forKey:DICT_CUSTOMER_INFO];
            //
            
            if (dictUserInfo!=nil) {
                if ([dictUserInfo valueForKey:@"UserAccount"]) {
                    [myDefaults setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:Login_UserAccount];
                }
                else
                {
                }
            }
            else
            {
            }

//            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//            delegate.viewController.lblUserName.text=strUserNameQQSina;
            for (UIViewController *objectView in [AppDelegate app].unc.viewControllers) {
                if ([objectView isKindOfClass:[ViewController class]]) {
                    ViewController *viewctrl=(ViewController *)objectView;
                    
                    viewctrl.lblUserName.text=strUserNameQQSina;
                    viewctrl.btnCancel.hidden=NO;
                    viewctrl.LoginInOrOut=NO;
                    [viewctrl.btnCancel setImage:[UIImage imageNamed:@"Loginout.png"] forState:UIControlStateNormal];
                    [self getNoticeNum];
                }
            }
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }

}

//-(void)setSinaQQRequest//向太保移动平台发送请求报文
//{
//    NSString *strRequestCode=@"RequestCode=62014";
//    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
//    [dicRequest setValue:@"" forKey:@"UserAccount"];
//    if (touchSina==YES && touchQQ==NO) {
//         SinaWeibo *sinaweibo = [self sinaweibo];
//        [dicRequest setValue:sinaweibo.userID forKey:@"UserId"];
//    }
//    else if(touchQQ==YES && touchSina==NO)
//    {
//        [dicRequest setValue:QQopenId forKey:@"UserId"];
//    }
//    else
//    {
//        [dicRequest setValue:@"" forKey:@"UserId"];
//    }
//    
//    [dicRequest setValue:@"" forKey:@"UserPassword"];
//    [dicRequest setValue:@"" forKey:@"IdentifyingCode"];
//    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
//    ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:myurl];
//    
//    [request setDelegate:self];
//    [request setDidFailSelector:@selector(ResponseSinaQQFail:)];
//    [request setDidFinishSelector:@selector(ResonseSinaQQSuccess:)];
//    [request startAsynchronous];
//    
//    showProgress = YES;
//    if (showProgress) {
//        NSLog(@"88888");
//        // [NSThread sleepForTimeInterval:1];
//        progress= [[MBProgressHUD alloc]initWithView:self.view];
//        [self.view addSubview:progress];
//        [self.view bringSubviewToFront:progress];
//        progress.labelText = @"查询中...";
//        [progress show:YES];
//        showProgress = NO;
//    }
//}
//
//- (void)ResonseSinaQQSuccess:(ASIHTTPRequest *)request
//{
//    if (!showProgress)
//    {
//        [progress removeFromSuperview];
//        progress = nil;
//    }
//    NSString *responseString = [request responseString];
//    NSLog(@"responseString %@",responseString);
//    NSMutableDictionary *dictResponse=[responseString JSONValue];
//    NSLog(@"dictResponse  %@",dictResponse);
//    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
//    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
//    NSLog(@"strResult%@",strResult);
//    if ([strResult isEqualToString:@"1"]) {
//        
//    }
//    else
//    {
//        
//    }
//    [strResult release];
//    
//    
//}
//
//- (void)ResponseSinaQQFail:(ASIHTTPRequest *)request
//{
//    if (!showProgress)
//    {
//        [progress removeFromSuperview];
//        progress = nil;
//    }
//    NSLog(@"服务器连接失败!");
//    [self justShowMessage:@"服务器连接失败" title:@"注意"];
//}
//

- (SinaWeibo *)sinaweibo
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}
- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //[self justShowMessage:@"授权成功" title:nil];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - SinaWeibo Delegate

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@ refresh_token = %@", sinaweibo.userID, sinaweibo.accessToken, sinaweibo.expirationDate,sinaweibo.refreshToken);
    [self storeAuthData];
    touchQQ=NO;
    touchSina=YES;
    [self setBindCheckRequest];
//    if (bindingSina==NO) {
//        //[self justShowMessage:@"你已经绑定本系统账户" title:@"提示"];
//    }
//    else
//    {
//        AppDelegate *appMyDelegate=[[UIApplication sharedApplication]delegate];
//        if (appMyDelegate.iLoginorAccountTag==1) {
//            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"你还没绑定本系统账户,是否立即跳到绑定界面" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
//            alert.tag=3;
//            [alert show];
//            [alert release];
//        }
//        else if(appMyDelegate.iLoginorAccountTag==2)
//        {
//            
//        }
//
//    }
    
}

- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogOut");

}

- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboLogInDidCancel");
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    NSLog(@"sinaweibo logInDidFailWithError %@", error);
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    NSLog(@"sinaweiboAccessTokenInvalidOrExpired %@", error);

}

#pragma mark - SinaWeiboRequest Delegate

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release], userInfo = nil;
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release], statuses = nil;
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post status \"%@\" failed!", postStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post status failed with error : %@", error);
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post image status \"%@\" failed!", postImageStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post image status failed with error : %@", error);
    }
    
    

}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release];
        userInfo = [result retain];
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release];
        statuses = [[result objectForKey:@"statuses"] retain];
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];        [alertView show];
        [alertView release];
        
        [postStatusText release], postStatusText = nil;
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        [postImageStatusText release], postImageStatusText = nil;
    }
    
}

- (void)storeAuthQQ
{
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              QQAccessToken, @"QQAccessToken",
                              QQopenId, @"QQopenId", nil];
    
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"Dict_QQAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark - TencentSessionDelegate 
/**
* Called when the user successfully logged in.
*/
- (void)tencentDidLogin {
	// 登录成功
    
    if (_tencentOAuth.accessToken
        && 0 != [_tencentOAuth.accessToken length])
    {
        QQAccessToken = _tencentOAuth.accessToken;
        QQopenId=_tencentOAuth.openId;
        
        [self storeAuthQQ];
        [self setBindCheckRequest];

    }
    else
    {
       QQAccessToken = @"登录不成功 没有获取accesstoken";
    }
    
}

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
	if (cancelled){
        //[self justShowMessage:@"用户取消登录" title:nil];
	}
	else {
        [self justShowMessage:@"登录失败" title:nil];
	}
	
}
/**
 * Called when the notNewWork.
 */
-(void)tencentDidNotNetWork
{
    [self justShowMessage:@"无网络连接，请设置网络" title:nil];
}

/**
 * Called when the logout.
 */
-(void)tencentDidLogout
{
     [self justShowMessage:@"退出登录成功，请重新登录" title:nil];
     QQAccessToken = @"";

    
}

-(void)dealloc
{
    [txtUserAccount release];
    [txtUserPassword release];
    [txtLoginType release];
    [txtLoginCity release];
    
    [arrLoginCity release];
    [arrLoginType release];
    [arrUser release];
    [TableViewUser release];
    [TableViewCity release];
    [super dealloc];
}

@end
